// 设备通信管理器 DeviceSocket.js

// CRC表
const CRC_TABLE = [
    0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241,
    0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440,
    0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40,
    0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841,
    0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40,
    0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41,
    0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641,
    0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 0x1040,
    0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240,
    0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441,
    0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41,
    0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840,
    0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41,
    0xEE01, 0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40,
    0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640,
    0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080, 0xE041,
    0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240,
    0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441,
    0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41,
    0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840,
    0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41,
    0xBE01, 0x7EC0, 0x7F80, 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40,
    0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640,
    0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041,
    0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241,
    0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440,
    0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40,
    0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841,
    0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40,
    0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41,
    0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641,
    0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040
];

/**
 * 设备通信类
 */
class DeviceSocket {
    constructor() {
        this.socketTask = null;  // Socket任务
        this.ip = '';            // IP地址
        this.port = '';          // 端口
        this.isConnected = false; // 连接状态
        this.heartbeatTimer = null; // 心跳计时器
        this.lastHeartbeatTime = 0; // 最后一次心跳时间
        this.connectionStatusCallback = null; // 连接状态回调
        this.messageCallback = null; // 消息接收回调
    }

    /**
     * 初始化连接
     * @param {string} ip - 设备IP地址
     * @param {string|number} port - 设备端口
     * @param {Function} statusCallback - 状态回调函数
     * @param {Function} messageCallback - 消息回调函数
     */
    connect(ip, port, statusCallback, messageCallback) {
        this.ip = ip;
        this.port = port;
        this.connectionStatusCallback = statusCallback;
        this.messageCallback = messageCallback;

        // 关闭现有连接
        this.disconnect();

        // 创建新的Socket连接
        this.socketTask = uni.connectSocket({
            url: `ws://${this.ip}:${this.port}`,
            success: () => {
                console.log('Socket连接请求已发送');
            },
            fail: (error) => {
                console.error('Socket连接请求发送失败', error);
                if (this.connectionStatusCallback) {
                    this.connectionStatusCallback(false, error);
                }
            }
        });

        // 监听Socket打开事件
        this.socketTask.onOpen(() => {
            console.log('Socket连接已打开');
            this.isConnected = true;
            this.lastHeartbeatTime = Date.now();
            this.startHeartbeatMonitor();
            if (this.connectionStatusCallback) {
                this.connectionStatusCallback(true);
            }
        });

        // 监听Socket关闭事件
        this.socketTask.onClose(() => {
            console.log('Socket连接已关闭');
            this.isConnected = false;
            this.clearHeartbeatMonitor();
            if (this.connectionStatusCallback) {
                this.connectionStatusCallback(false);
            }
        });

        // 监听Socket错误事件
        this.socketTask.onError((error) => {
            console.error('Socket连接错误', error);
            this.isConnected = false;
            this.clearHeartbeatMonitor();
            if (this.connectionStatusCallback) {
                this.connectionStatusCallback(false, error);
            }
        });

        // 监听Socket消息事件
        this.socketTask.onMessage((res) => {
            this.handleMessage(res.data);
        });
    }

    /**
     * 断开连接
     */
    disconnect() {
        this.clearHeartbeatMonitor();
        if (this.socketTask && this.isConnected) {
            this.socketTask.close({
                success: () => {
                    console.log('Socket连接已主动关闭');
                    this.isConnected = false;
                }
            });
        }
        this.socketTask = null;
    }

    /**
     * 启动心跳监控
     */
    startHeartbeatMonitor() {
        this.clearHeartbeatMonitor();
        this.heartbeatTimer = setInterval(() => {
            const currentTime = Date.now();
            // 如果超过30秒没有收到心跳，认为连接已断开
            if (currentTime - this.lastHeartbeatTime > 30000) {
                console.log('心跳超时，断开连接');
                this.disconnect();
                if (this.connectionStatusCallback) {
                    this.connectionStatusCallback(false, { message: '心跳超时' });
                }
            }
        }, 5000); // 每5秒检查一次
    }

    /**
     * 清除心跳监控
     */
    clearHeartbeatMonitor() {
        if (this.heartbeatTimer) {
            clearInterval(this.heartbeatTimer);
            this.heartbeatTimer = null;
        }
    }

    /**
     * 处理接收到的消息
     * @param {*} data - 接收到的数据
     */
    handleMessage(data) {
        if (!data) return;

        try {
            // 如果数据是字符串格式，转为ArrayBuffer
            let arrayBuffer;
            if (typeof data === 'string') {
                // 假设数据是十六进制字符串，转换为ArrayBuffer
                arrayBuffer = this.hexStringToArrayBuffer(data);
            } else if (data instanceof ArrayBuffer) {
                arrayBuffer = data;
            } else {
                console.error('不支持的数据格式', data);
                return;
            }

            // 转换为Uint8Array处理
            const dataView = new Uint8Array(arrayBuffer);

            // 检查是否是心跳数据
            if (this.isHeartbeatPacket(dataView)) {
                // 更新最后心跳时间
                this.lastHeartbeatTime = Date.now();
                console.log('接收到心跳数据');

                // 心跳数据原样返回
                this.sendHexData(this.arrayBufferToHexString(arrayBuffer));

                // 回调心跳消息
                if (this.messageCallback) {
                    this.messageCallback({
                        isHeartbeat: true,
                        data: Array.from(dataView)
                    });
                }
                return;
            }

            // 检查是否是"OK!"响应 (4F 4B 21)
            if (dataView.length === 3 && dataView[0] === 0x4F && dataView[1] === 0x4B && dataView[2] === 0x21) {
                console.log('接收到OK响应');
                if (this.messageCallback) {
                    this.messageCallback({
                        format: 'OK_RESPONSE',
                        success: true,
                        message: 'OK!',
                        rawData: Array.from(dataView)
                    });
                }
                return;
            }

            // 检查是否是EE FF格式的烟感响应
            if (dataView.length >= 4 && dataView[0] === 0xEE && dataView[1] === 0xFF) {
                console.log('接收到烟感响应');
                // 烟感响应格式: EE FF C0 01 00 state 0D xx xx
                if (dataView.length >= 9) {
                    const command = dataView[2]; // 通常是C0
                    const address = dataView[3]; // 通常是01
                    const alarmState = dataView[5]; // 0=无报警, 1=有报警

                    if (this.messageCallback) {
                        this.messageCallback({
                            format: 'SMOKE_SENSOR',
                            commandType: 'SMOKE_SENSOR', // 此处应与CommandType.SMOKE_SENSOR匹配
                            command: command,
                            address: address,
                            hasAlarm: alarmState === 0x01,
                            rawData: Array.from(dataView),
                            parsedData: {
                                hasAlarm: alarmState === 0x01,
                                status: alarmState === 0x01 ? '有报警' : '无报警'
                            }
                        });
                    }
                }
                return;
            }

            // 尝试导入命令发送器
            let DeviceCommandSender;
            try {
                DeviceCommandSender = require('./DeviceCommandSender.js').default;
            } catch(e) {
                // 如果导入失败，使用原有的解析方法
                const parsed = this.parseModbusData(dataView);
                if (parsed && this.messageCallback) {
                    this.messageCallback(parsed);
                }
                return;
            }

            // 使用命令发送器解析响应
            const response = DeviceCommandSender.parseResponse(dataView);
            if (response) {
                console.log('解析设备响应成功:', response);

                if (this.messageCallback) {
                    this.messageCallback(response);
                }
            } else {
                console.error('无法解析设备响应');
                // 返回原始数据，让上层应用决定如何处理
                if (this.messageCallback) {
                    this.messageCallback({
                        format: 'UNKNOWN',
                        rawData: Array.from(dataView)
                    });
                }
            }
        } catch (error) {
            console.error('处理消息异常:', error);
        }
    }

    /**
     * 判断是否是心跳包
     * @param {Uint8Array} data - 待检查的数据
     * @returns {boolean} - 是否是心跳包
     */
    isHeartbeatPacket(data) {
        // 心跳数据固定为: A5 00 12 59 4A A1 B2 C3 D4 E5 F6 A7 B8 C9 D0 F1 F2 EA
        if (data.length !== 18) return false;

        const heartbeatPattern = [
            0xA5, 0x00, 0x12, 0x59, 0x4A, 0xA1, 0xB2, 0xC3,
            0xD4, 0xE5, 0xF6, 0xA7, 0xB8, 0xC9, 0xD0, 0xF1, 0xF2, 0xEA
        ];

        // 匹配前几个字节即可确认是心跳包
        for (let i = 0; i < 3; i++) {
            if (data[i] !== heartbeatPattern[i]) return false;
        }

        return true;
    }

    /**
     * 解析Modbus数据
     * @param {Uint8Array} data - 接收到的数据
     * @returns {Object|null} - 解析结果，验证失败返回null
     */
    parseModbusData(data) {
        // 检查数据至少包含最小Modbus帧的长度
        if (data.length < 6) return null;

        const address = data[0];       // 地址码
        const functionCode = data[1];  // 功能码
        const byteCount = data[2];     // 返回的有效字节数

        // 验证数据长度是否符合预期
        if (data.length < 3 + byteCount + 2) return null;

        // 提取有效数据部分
        const validData = data.slice(3, 3 + byteCount);

        // 提取CRC校验码（低字节在前，高字节在后）
        const receivedCRC = (data[3 + byteCount + 1] << 8) | data[3 + byteCount];

        // 计算校验码
        const calculatedCRC = this.calculateCRC(data.slice(0, 3 + byteCount));

        // 验证CRC
        if (receivedCRC !== calculatedCRC) {
            console.error('CRC校验失败，数据可能损坏');
            return null;
        }

        return {
            address: address,
            functionCode: functionCode,
            byteCount: byteCount,
            data: Array.from(validData),  // 转换为普通数组便于使用
            crc: receivedCRC
        };
    }

    /**
     * 发送十六进制数据
     * @param {string} hexString - 十六进制字符串，如"A5 00 12"
     * @returns {boolean} - 是否发送成功
     */
    sendHexData(hexString) {
        if (!this.isConnected || !this.socketTask) {
            console.error('Socket未连接，无法发送数据');
            return false;
        }

        try {
            // 去除可能存在的空格
            const cleanHexString = hexString.replace(/\s+/g, '');

            // 检查是否为有效的十六进制字符串
            if (cleanHexString.length % 2 !== 0 || !/^[0-9A-Fa-f]+$/.test(cleanHexString)) {
                console.error('无效的十六进制字符串:', hexString);
                return false;
            }

            const arrayBuffer = this.hexStringToArrayBuffer(hexString);
            this.socketTask.send({
                data: arrayBuffer,
                success: () => {
                    console.log('数据发送成功:', hexString);
                },
                fail: (error) => {
                    console.error('数据发送失败:', error);
                }
            });
            return true;
        } catch (error) {
            console.error('发送数据异常:', error);
            return false;
        }
    }

    /**
     * 发送Modbus命令
     * @param {number} address - 设备地址
     * @param {number} functionCode - 功能码
     * @param {Array} data - 数据部分
     * @returns {boolean} - 是否发送成功
     */
    sendModbusCommand(address, functionCode, data) {
        if (!this.isConnected || !this.socketTask) {
            console.error('Socket未连接，无法发送数据');
            return false;
        }

        try {
            // 构建命令数据
            const commandData = [address, functionCode, ...data];

            // 计算CRC
            const crc = this.calculateCRC(commandData);

            // 添加CRC（低字节在前，高字节在后）
            commandData.push(crc & 0xFF);
            commandData.push((crc >> 8) & 0xFF);

            // 转换为十六进制字符串
            const hexString = this.arrayToHexString(commandData);

            // 发送数据
            return this.sendHexData(hexString);
        } catch (error) {
            console.error('发送Modbus命令异常:', error);
            return false;
        }
    }

    /**
     * 计算CRC校验值
     * @param {Array|Uint8Array} data - 需要计算CRC的字节数组
     * @return {number} - 计算得到的CRC值
     */
    calculateCRC(data) {
        let crc = 0xFFFF;
        for (let i = 0; i < data.length; i++) {
            // 在JavaScript中需要确保值在0-255之间
            const b = data[i] & 0xFF;
            crc = ((crc >>> 8) ^ CRC_TABLE[(crc ^ b) & 0xFF]) & 0xFFFF;
        }
        return crc;
    }

    /**
     * 将十六进制字符串转换为ArrayBuffer
     * @param {string} hexString - 十六进制字符串，如"A5 00 12"
     * @returns {ArrayBuffer} - 转换后的ArrayBuffer
     */
    hexStringToArrayBuffer(hexString) {
        // 移除所有空格
        hexString = hexString.replace(/\s+/g, '');

        if (hexString.length % 2 !== 0) {
            throw new Error('十六进制字符串长度必须是偶数');
        }

        const buffer = new ArrayBuffer(hexString.length / 2);
        const dataView = new Uint8Array(buffer);

        for (let i = 0; i < hexString.length; i += 2) {
            dataView[i / 2] = parseInt(hexString.substr(i, 2), 16);
        }

        return buffer;
    }

    /**
     * 将ArrayBuffer转换为十六进制字符串
     * @param {ArrayBuffer} buffer - ArrayBuffer数据
     * @returns {string} - 转换后的十六进制字符串，如"A5 00 12"
     */
    arrayBufferToHexString(buffer) {
        const dataView = new Uint8Array(buffer);
        return this.arrayToHexString(dataView);
    }

    /**
     * 将数组转换为十六进制字符串
     * @param {Array|Uint8Array} array - 字节数组
     * @returns {string} - 转换后的十六进制字符串，如"A5 00 12"
     */
    arrayToHexString(array) {
        return Array.from(array)
            .map(byte => byte.toString(16).padStart(2, '0').toUpperCase())
            .join(' ');
    }
}

// 导出设备通信类的实例
export default new DeviceSocket();